package edu.wayne.cs.csc4110.hw6.framework.lobby;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;

import edu.wayne.cs.csc4110.hw6.interfaces.lobby.LobbyClient;
import edu.wayne.cs.csc4110.hw6.interfaces.lobby.LobbyServer;
import edu.wayne.cs.csc4110.hw6.interfaces.message.Message;
import edu.wayne.cs.csc4110.hw6.interfaces.user.User;

/**
 * GameLobbyServer collects and manages user data keeps server updated by adding
 * new users/clients and deleting obsolete users/clients
 */
public class GameLobbyServer extends Observable implements LobbyServer {

	private static GameLobbyServer server = null;

	private List<User> users = new ArrayList<User>();

	@Override
	public List<User> getUsers() {
		return users;
	}

	@Override
	public boolean addUser(User user) {
		setChanged();
		notifyObservers(user);
		return users.add(user);
	}



	@Override
	public boolean removeUser(User user) {
		setChanged();
		notifyObservers(user);
		return users.remove(user);

	}

	@Override
	public void addClient(LobbyClient c) {
		this.addObserver(c);

	}

	@Override
	public void deleteClient(LobbyClient c) {
		this.deleteObserver(c);

	}

	public static LobbyServer getInstance() {
		if (server == null) {
			server = new GameLobbyServer();
		}
		return server;
	}

	@Override
	public void sendMessage(Message msg) {
		setChanged();
		notifyObservers(msg);

	}

	@Override
	public User getUser(String name) {
		for (User u : getUsers()) {
			if (u.getUsername().equals(name))
				return u;
		}
		return null;
	}

}
